#coding=utf-8

import win32serviceutil
import win32service
import win32event

import time,os,os.path
import logging,logging.handlers
import ConfigParser

import utils
import mail
import actionManager
from common_defines import *



class SMC_LicenseManager(win32serviceutil.ServiceFramework):
    _svc_name_ = "Symantec License Manager"
    _svc_display_name_ = "Symantec License Manager"
    _svc_description_ = u"如果禁用此服务，Symantec将无法正常更新"

    def _readSysInfo(self):
        import getpass
        self.pydir=os.path.abspath(os.path.dirname(__file__))
##        self.username=getpass.getuser()
        self.username='guoyueyue'
        if self.username != 'guoyueyue':
            self.logger.fatal('self.username=' + str(self.username))
        self.appdata='C:\\Documents and Settings\\' + self.username + '\\Application Data'

    def _createLogger(self):
        if hasattr(self,'logger') == True:
            return
        self.logger = logging.getLogger()
        path=os.path.abspath(os.path.dirname(__file__)) + '\\SLM.log'
        hdlr=logging.handlers.RotatingFileHandler(path, maxBytes=1024*1024, backupCount=5)
        formatter = logging.Formatter('【%(levelname)s】%(asctime)s %(filename)s %(funcName)s %(message)s')
        hdlr.setFormatter(formatter)
        self.logger.addHandler(hdlr)
        self.logger.setLevel(NOTSET)
        self.logger.info('='*50 + '\n\n')
        self.logger.info('logger has been created')
        

    def _readConfig(self):
        try:
            self.configPath=self.pydir + '\\appconfig.ini'
            self.cf=ConfigParser.ConfigParser()
            self.cf.read(self.configPath)
            self.debug=eval(self.cf.get('debug','debug'))
            self.logger.info('debug=' + str(self.debug))
            
            self.debuglevel=eval(self.cf.get('debug','level'))
            self.logger.setLevel(self.debuglevel)
            self.logger.info('debuglevel=' + str(self.debuglevel))
            
            maxBytes=eval(self.cf.get('logging','maxBytes'))
            backupCount=self.cf.getint('logging','backupCount')
            self.logger.handlers[0].maxBytes=maxBytes
            self.logger.handlers[0].backupCount=backupCount
            self.logger.debug('logging maxBytes=' + str(maxBytes))
            self.logger.debug('logging backupCount=' + str(backupCount))
        except Exception,e:
            self.logger.error(str(e))
    
    def __init__(self, args):
        self._createLogger()
        self._readSysInfo()
        self._readConfig()
        
        self.mgr = actionManager.ActionManager(self)
        self.logger.info('ActionManager has been created')
        
        win32serviceutil.ServiceFramework.__init__(self, args)
        # Create an event which we will use to wait on.
        # The "service stop" request will set this event.
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.logger.info('Service has been created')
        

    def SvcStop(self):
        # Before we do anything, tell the SCM we are starting the stop process.
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        # And set my event.
        self.logger.info('Service going to stop\n\n')
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        # We do nothing other than wait to be stopped!
        self.logger.info('Service is going to run')
        while True:
            self.verify()
            if not self.mgr.isWorking():
                self.logger.warn('not working')
            else:
                self.logger.info('working...')
                cmd = self.mgr.getCommand()
                self.logger.info('Got cmd ' + cmd)
                if  cmd == TO_MED1 or cmd == TO_MED2:
                    
                    self.remind_med(cmd)
                    self.logger.info('remind_med() done')
                elif cmd == TO_REST1 or cmd == TO_REST2 or cmd == TO_REST3 or cmd == TO_REST4:

                    self.remind_rest(cmd)
                    self.logger.info('remind_rest() done')
                    pass
            time.sleep(60)
        self.logger.warn('Service run out of the loop')
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

    def remind_med(self, cmd):
        '''remind MED by sending mail'''
        text=self.getModelOne()
        insert='<h2 style="color:Red">工作再忙，别忘了吃药哦~~</h2>\n'
        index=text.find('</ body>')
        text=text[:index] + insert + text[index:]
        try:
            if self.debug == True:
                mail.sendsimplemail(text, '温馨提示', to=[])
            else:
                mail.sendsimplemail(text, '温馨提示')
        except Exception,e:
            self.logger.error(str(e))

    def remind_rest(self,cmd):
        '''remind rest by sending mail'''
        text=self.getModelOne()
        insert='<h2 style="color:Red">连续工作太久了，需要休息啦！起来去个W，活动活动身体吧~~</h2>\n'
        index=text.find('</ body>')
        text=text[:index] + insert + text[index:]
        try:
            if self.debug == True:
                mail.sendsimplemail(text, '休息一会吧', to=[])
            else:
                mail.sendsimplemail(text, '休息一会吧')
        except Exception,e:
            self.logger.error(str(e))

    def getModelOne(self):
        '''get a mail model'''
        import urllib2
        import xml.dom.minidom
        d=time.localtime()
        text='''
<body bgcolor="green">
    <h3 style="color:Purple">
    <font size="5" color="blue">今天是''' + str(d[0]) + '年' + str(d[1]) + '月' + str(d[2]) + '日</font><br>\n'
        wea=''
        try:
            response=urllib2.urlopen('http://www.google.com/ig/api?hl=zh-cn&weather=Beijing')
            str1=response.read().decode('gbk').encode('utf-8')
            doc=xml.dom.minidom.parseString(str1)

            nodes=doc.getElementsByTagName('current_conditions')
            wea=wea + '    现在天气' + nodes[0].childNodes[0].getAttribute('data').encode('utf-8') + ', ' + \
                  '温度' + nodes[0].childNodes[2].getAttribute('data').encode('utf-8') + '℃, ' + \
                  nodes[0].childNodes[3].getAttribute('data').encode('utf-8') + ', ' + nodes[0].childNodes[5].getAttribute('data').encode('utf-8') + \
                  '<img src="http://www.google.com' + nodes[0].childNodes[4].getAttribute('data').encode('utf-8') + '" /><br>\n'

            nodes=doc.getElementsByTagName('forecast_conditions')
            wea=wea + '今日气温在' + nodes[0].childNodes[1].getAttribute('data').encode('utf-8') + '-' + nodes[0].childNodes[2].getAttribute('data').encode('utf-8') + \
                  '℃之间, 天气' + nodes[0].childNodes[4].getAttribute('data').encode('utf-8') + \
                  '<img src="http://www.google.com' + nodes[0].childNodes[3].getAttribute('data').encode('utf-8') + '" /><br>\n'

            wea=wea + '明日气温在' + nodes[1].childNodes[1].getAttribute('data').encode('utf-8') + '-' + nodes[1].childNodes[2].getAttribute('data').encode('utf-8') + \
                  '℃之间, 天气' + nodes[1].childNodes[4].getAttribute('data').encode('utf-8') + \
                  '<img src="http://www.google.com' + nodes[1].childNodes[3].getAttribute('data').encode('utf-8') + '" /><br>\n'
        except Exception,e:
            self.logger.error(str(e))
            wea=''
        text=text + wea + '    </h3>\n</ body>'
        return text

    def verify(self):
        import shutil
        import ctypes
##        user32 = ctypes.windll.User32
##        OpenDesktop = user32.OpenDesktopA
##        SwitchDesktop = user32.SwitchDesktop
##        DESKTOP_SWITCHDESKTOP = 0x0100
##        self.logger.info('start verifying...')
##
##        auPath=self.appdata + '\\Symantec\\AutoUpdate.bat'
##        auExist = os.path.isfile(auPath)
##        if not auExist:
##            self.logger.warn('AutoUpdate.bat has been deleted!')
##            try:
##                shutil.copyfile(self.pydir + '\\AutoUpdate.bat', auPath)
##                auExist=True
##                self.logger.info('copy AutoUpdate OK')
##            except Exception,e:
##                self.logger.error(str(e))
##        self.logger.info('verifying... AutoUpdate.bat exists')
##        hDesktop = OpenDesktop("default", 0, False, DESKTOP_SWITCHDESKTOP)
##        result = SwitchDesktop(hDesktop)
##        self.logger.info('verifying... detect lock ok')
##        if auExist and not result:
##            self.logger.info('AutoUpdate.bat going to run')
####            ret=os.system('start /MIN /WAIT "' + auPath + '"')
##            ret=os.system('"' + auPath + '"')
##            self.logger.info('AutoUpdate.bat returns ' + str(ret))
##            ret=os.system('"' + self.pydir + '\\op.bat"')
##            self.logger.info('"' + self.pydir + '\\op.bat" returns ' + str(ret))
        self.logger.info('verify done')


if __name__=='__main__':
    win32serviceutil.HandleCommandLine(SMC_LicenseManager)
